using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;
using TagLib;

namespace AnTunes
{
	public abstract class TrackInfo
	{
		protected TrackInfo (Track track)
		{
			track_ = track;
		}
		
		public TrackMeta Meta
		{
			get
			{
				if(meta_ == null)
				{
					UpdateMeta();
				}
				return meta_;
			}
			protected set
			{
				meta_ = value;
			}
		}
		
		public abstract string Name
		{
			get;
		}
		
		public string Hash
		{
			get
			{
				if(hash_ == null)
				{
					UpdateHash();
				}
				return hash_;
			}
			protected set
			{
				hash_ = value;
			}
		}
		
		protected void UpdateMeta()
		{
			TagLib.File tagFile = TagLib.File.Create(new Id3StreamReader(Name, track_.OpenStream()));
			TagLib.Tag tag = tagFile.Tag;
			meta_ = new TrackMeta();
			meta_.Album = tag.Album;
			meta_.Artist = tag.JoinedPerformers;
			meta_.Comment = tag.Comment;
			meta_.Genres = tag.Genres;
			if(tag.Pictures != null)
			{
				MemoryStream stream = new MemoryStream(tag.Pictures[0].Data.Data);
				meta_.Picture = new System.Drawing.Bitmap(stream);
			}
			meta_.Title = tag.Title;
			meta_.TrackNumber = tag.Track;
			meta_.Year = tag.Year;                    
		}
		
		protected virtual void UpdateHash()
		{	
			MD5 md5 = MD5.Create();
			md5.Initialize();
			byte[] hashBytes = md5.ComputeHash(track_.OpenStream());
			hash_ = Convert.ToBase64String(hashBytes);
		}
		
		protected string hash_;
		protected TrackMeta meta_;
		protected Track track_;
	}
}

